package com.xiyuan.smartutils.template.engine.expression.operator.logic;

import com.xiyuan.smartutils.template.engine.VariableMap;
import com.xiyuan.smartutils.template.engine.exception.ExpressionException;
import com.xiyuan.smartutils.template.engine.expression.Expression;
import com.xiyuan.smartutils.template.engine.expression.operator.Operator;

/**
 * 三目运算（?a:b）
 * @version v1.0.0 @author lgz 2020年12月9日 新建与整理
 */
public class _Ternary extends Operator
{
    private static final long serialVersionUID = 1L;
    private Expression condition;
    private Expression first;
    private Expression second;
    
    public _Ternary(String path, int line, int column, Expression condition, Expression first, Expression second)
    {
        super(path, line, column);
        this.condition = condition;
        this.first = first;
        this.second = second;
        this.assertSymbo("三目", condition, first, second);
    }
    
    @Override
    public int getType()
    {
        return TERNARY;
    }
    
    @Override
    protected Object build(VariableMap variableMap)
    {
        Object value = condition.execute(variableMap);
        if (value == null)// 为null时，采用js的规则，判断为false
            return second.execute(variableMap);
        
        if (value instanceof Boolean)
        {// 值为boolean型
            return ((Boolean) value) ? first.execute(variableMap) : second.execute(variableMap);
        }
        
        // 非null且非boolean的不支持
        throw new ExpressionException(this, "三目表达式{" + this + "}格式不正确，条件结果不是布尔型");
    }

    @Override
    public String toString()
    {
        return new StringBuilder(condition.toString()).append(" ? ").append(first).append(" : ").append(second).toString();
    }
}
